<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-10 18:37:27
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-06-18 16:08:10
 * @Description: 
-->

<template>
    <el-row>
        <el-col :span="24">
            <el-row>
                <el-col :span="24">
                    <el-card class="task-list-container">
                        <el-row>
                            <el-col :span="24" style="padding:0 0 10px 0" class="task-list-header">
                                <div class="search-container">
                                    <el-input size="small" placeholder="算法查询" :prefix-icon="Search" style="width: 200px;"
                                        v-model="keyword" clearable></el-input>
                                    <el-button size="small" type="primary" @click="">搜索</el-button>
                                </div>
                            </el-col>
                            <el-table :border="true" size="small" :data="tableData" style="width: 100%"
                                :height="view.height - 315">
                                <el-table-column :align="'center'" type="index" label="序号" width="60" />
                                <el-table-column :align="'center'" prop="name" label="任务名称">
                                    <template #default="scope">
                                        <el-link size="small" style="font-size: 12px;" type="primary">
                                            {{ scope.row.name }}
                                        </el-link>
                                    </template>
                                </el-table-column>
                                <el-table-column :align="'center'" prop="status" label="任务状态" width="120">
                                    <template #default="scope">
                                        <el-tag :type="customSattus(scope.row.status).status">{{
                                            customSattus(scope.row.status).text }}</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column :align="'center'" prop="progress" label="任务进度" width="220">
                                    <template #default="scope">
                                        <div style="display: flex;justify-content:center">
                                            <el-progress style="width:200px" :percentage="scope.row.progress"
                                                :color="customColors" />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column :align="'center'" prop="createDate" label="创建日期" width="180">
                                    <template #default="scope">
                                        {{ utils.formatDate(scope.row.createDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column :align="'center'" prop="updateDate" label="结束日期" width="180">
                                    <template #default="scope">
                                        {{ utils.formatDate(scope.row.updateDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column :align="'center'" label="操作" width="100">
                                    <template #default="scope">
                                        <!-- <el-link type="primary" @click.stop="">日志</el-link> &nbsp; -->
                                        <el-button-group>
                                            <el-popconfirm title="确定要删除当前任务么?" @confirm="deleteTask(scope.row)">
                                                <template #reference>
                                                    <el-link type="danger" @click.stop="">删除</el-link>
                                                </template>
                                            </el-popconfirm>
                                        </el-button-group>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-row>
                        <template #footer>
                            <div style="margin-top:5px;width: 100%;">
                                <pagination-com :pagination="taskPagination" @handleSizeChange="taskSizeChangeHanlder"
                                    @handleCurrentChange="taskIndexChangeHanlder"></pagination-com>
                            </div>
                        </template>
                    </el-card>
                </el-col>
            </el-row>
        </el-col>
    </el-row>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, onBeforeUnmount, watch } from "vue";
import {
    Check,
    Delete,
    Message,
    Search,
    Star,
    Setting,
    Upload,
    Plus, VideoPlay, CaretRight, InfoFilled, Edit
} from "@element-plus/icons-vue";
// import * as _ from "lodash";
import utils from '@/utils/util'
import { ElMessage, ElMessageBox } from "element-plus";
import HttpService from "@/api/api";
import paginationCom from "@/components/pagination/paginationCom.vue";
import router from "@/router";
let keyword = ref('')
let tableData = ref([])
let tableLoading = ref(false)
const socket = ref(null);
const isConnected = ref(false);
const autoSeg = ref(false)
const loading1 = ref(false)

let taskPagination = reactive({
    page_index: 1,
    page_size: 15,
    page_total: 0,
});

const customColors = [
    { color: '#f56c6c', percentage: 20 },
    { color: '#e6a23c', percentage: 40 },
    { color: '#5cb87a', percentage: 60 },
    { color: '#1989fa', percentage: 80 },
    { color: '#6f7ad3', percentage: 100 },
]

const customSattus :any = function (status) {
    let result = {
        text: "编辑中",
        status: "primary"
    }
    switch (status) {
        case 0:
            result.text = "未开始"
            result.status = "info"
            break;
        case 1:
            result.text = "处理成功"
            result.status = "success"

            break;
        case 3:
            result.text = '处理失败'
            result.status = "error"

            break;
        case 2:
            result.text = '执行中'
            result.status = "warning"
            break;
        case 4:
            result.text = '发布完成'
            result.status = "warning "
            break;
        case 5:
            result.text = '已编辑'
            result.status = "primary"
            break;
        case 6:
            result.text = '已推送'
            result.status = "success"
            break;
        default:
            result.text = '编辑中'
            result.status = "primary"
            break;
    }
    return result;
}
var view = reactive({
    height: window.innerHeight,
});

const getTasks = function () {
    let params = {
        page_size: taskPagination.page_size,
        page_index: taskPagination.page_index,
        keyword: keyword.value
    };
    tableData.value.length = 0;
    tableLoading.value = true
    HttpService.taskManage.getTasks(
        params,
        (res) => {
            if (res.status == 200) {
                res.data.data.map((item, index) => {
                    tableData.value.push(item);
                    tableLoading.value = false
                });
                taskPagination.page_total = res.data.total
            } else {
                console.log("获取信息失败" + res);
                tableLoading.value = false
            }
        },
        (error) => {
            console.log(error);

            tableLoading.value = false
        }
    );
}

const deleteTask = function (task) {
    let params = {
        id: task.id
    };
    HttpService.taskManage.deleteTask(
        params,
        (res) => {

            if (res.status == 200) {
                ElMessage({
                    message: "删除成功 ",
                    type: "success",
                });
                getTasks()
            } else {
                ElMessage({
                    message: res,
                    type: "error",
                });
            }
        },
        (error) => {
            console.log(error);
        }
    );
}

const publishHandler = function (task) {
    let params = {
        id: task.id
    };
    HttpService.taskManage.publishResult(
        params,
        async (res) => {
            if (res.status == 200) {
                ElMessage({
                    message: "发布成功 ",
                    type: "success",
                });
            } else {
                ElMessage({
                    message: res,
                    type: "error",
                });
            }
            getTasks()
        },
        (error) => {
            console.log(error);
        }
    );
}



const taskSizeChangeHanlder = function (page_size: number) {
    taskPagination.page_size = page_size;
    getTasks();
};
const taskIndexChangeHanlder = function (page_index: number) {
    taskPagination.page_index = page_index;
    getTasks();
};

const handleCurrentChange = function (val) {
    console.log(val)
}

const previewLayerHandler = function () {
    router.push('/index/general/executeManage/previewLayers')
}

getTasks()

const baseURL = "localhost"
// const baseURL = "192.168.101.207"

socket.value = new WebSocket(`ws://${baseURL}:8001/webSocket`);
socket.value.onopen = () => {
    console.log('WebSocket connected');
    isConnected.value = true;
};
socket.value.onmessage = (event) => {
    const data = JSON.parse(event.data);
    const { cmd, action } = data
    if (cmd == 'task') {
        if (action == "refresh") {
            getTasks();
        }
    }
};
socket.value.onclose = () => {
    console.log('WebSocket disconnected');
    isConnected.value = false;
};

const sendMessage = () => {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
        const message = 'Hello WebSocket';
        socket.value.send(message);
    } else {
        console.log('WebSocket is not connected');
    }
};

const beforeChange1 = async () => {
    loading1.value = true
    return new Promise((resolve) => {
        setTimeout(() => {
            statusListen()
            return resolve(true)
        }, 1000)
    })
}

const statusListen = function () {
    let params = {
        status: !autoSeg.value
    }
    HttpService.taskManage.statusListen(
        params,
        (res) => {
            if (res.status == 200) {
                ElMessage({
                    message: res.data.message,
                    type: "success",
                });
                loading1.value = false
            } else {
                ElMessage({
                    message: "自动处理状态切换失败 ",
                    type: "error",
                });
                loading1.value = false
            }
        },
        (error) => {
            console.log(error);
            ElMessage({
                message: "自动处理状态切换失败 ",
                type: "error",
            });
            loading1.value = false
        }
    );
}


onMounted(() => {
    sendMessage()
});

</script>
<style lang="scss" scoped>
.search-container {
    width: 260px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.task-list-header {
    display: flex;
    justify-content: space-between;
}

.card-header {
    display: flex;
    justify-content: space-between;
}
</style>
<style lang="scss">
.task-list-container {
    padding: 10px 0 0;
    width: 100%;

    .current-row {
        .el-table__cell {
            background: var(--el-color-primary-light-3) !important;
            color: var(--el-color-white);
            transition: all 0.5s;

            .el-link {
                color: #fff;
            }
        }
    }

    .el-table__row {
        cursor: pointer;
    }
}
</style>